package com.generate.tools.generate;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.generate.tools.main.IMaster;
import com.generate.tools.utils.PropertiesUtil;
import com.generate.tools.utils.StringUtils;

public class GenerateEntityMysql extends AbstractGenerateEntity implements IMaster {
	private static final Logger logger = LoggerFactory.getLogger(GenerateEntityMysql.class);
	private String packageOutPath = PropertiesUtil.read("entityPath", PRO_CONFIG);// 指定实体生成所在包的路径
	private String mapperOutPath = PropertiesUtil.read("mapperPath", PRO_CONFIG);// 指定实体生成所在包的路径
	private String prefix = PropertiesUtil.read("prefix", PRO_CONFIG);
	private String[] colnames; // 列名数组
	private String[] colTypes; // 列名类型数组
	private int[] colSizes; // 列名大小数组
	private String tableName = "";
	private static final String PRO_CONFIG = "gen";

	private Map<String, String> getColumnCommentMap(Connection conn, String tablename) {
		try {
			String sql = "select COLUMN_COMMENT,COLUMN_NAME,TABLE_NAME from   Information_schema.columns c where c.table_name=?";
			PreparedStatement pStemt = conn.prepareStatement(sql);
			pStemt.setString(1, tablename);
			ResultSet rs = pStemt.executeQuery();
			Map<String, String> map = new HashMap<String, String>();
			while (rs.next()) {
				map.put(rs.getString("COLUMN_NAME"), rs.getString("COLUMN_COMMENT"));
			}
			return map;
		} catch (Exception e) {
			return new HashMap<String, String>();
		}
	}
	
	private Map<String, String> getTableCommentMap(Connection conn, String tablename) {
		try {
			String sql = "select TABLE_COMMENT,TABLE_NAME from   Information_schema.tables c where c.table_name=?";
			PreparedStatement pStemt = conn.prepareStatement(sql);
			pStemt.setString(1, tablename);
			ResultSet rs = pStemt.executeQuery();
			Map<String, String> map = new HashMap<String, String>();
			while (rs.next()) {
				map.put(rs.getString("TABLE_NAME") , rs.getString("TABLE_COMMENT"));
			}
			return map;
		} catch (Exception e) {
			return new HashMap<String, String>();
		}
	}

	/*
	 * 构造函数
	 */
	public void generate(Connection conn) {
		String tableNameStr = PropertiesUtil.read("tableName", PRO_CONFIG);
		logger.info("table:" + tableNameStr);
		List<String> tableNames = Arrays.asList(tableNameStr.split(","));
		// 查要生成实体类的表
		PreparedStatement pStemt = null;
		try {
			for (String name : tableNames) {
				Map<String, String> commentMap = getColumnCommentMap(conn, name);
				Map<String, String> tableCommentMap = getTableCommentMap(conn, name);
				tableName = name.toLowerCase();
				String sql = "select * from " + tableName;
				pStemt = conn.prepareStatement(sql);
				ResultSetMetaData rsmd = pStemt.getMetaData();
				int size = rsmd.getColumnCount(); // 统计列
				colnames = new String[size];
				colTypes = new String[size];
				colSizes = new int[size];
				for (int i = 0; i < size; i++) {
					colnames[i] = rsmd.getColumnName(i + 1).toLowerCase();
					colTypes[i] = rsmd.getColumnTypeName(i + 1);
					if (colTypes[i].equalsIgnoreCase("datetime") || colTypes[i].equalsIgnoreCase("timestamp")) {
						f_util = true;
					}
					if (colTypes[i].equalsIgnoreCase("image") || colTypes[i].equalsIgnoreCase("text")) {
						f_sql = true;
					}
					colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
				}
				super.setColTypes(colTypes);
				super.setColumns(colnames);
				super.setColumnSizes(colSizes);
				super.setPackageName(packageOutPath);
				super.setPrefix(sql);
				super.setTableName(tableName);
				super.setMapperPackageName(mapperOutPath);
				super.setClassName(StringUtils.upperCase(getClassName(tableName,prefix)));
				final String content = parse(commentMap,tableCommentMap);
				logger.info("content:"+content);
				String absolutePath = getAbsolutePath() + File.separator
						+ this.packageOutPath.replace(".", File.separator) + File.separator;
				final String outputPath = absolutePath + super.getClassName() + ".java";
				File file = new File(absolutePath);
				if (!file.exists()) {
					file.mkdirs();
				}
				System.out.println(outputPath);
				FileWriter fw = new FileWriter(outputPath);
				PrintWriter pw = new PrintWriter(fw);
				pw.println(content);
				pw.flush();
				pw.close();
				
				String mapperAbsolutePath = getAbsolutePath() +  File.separator
				+ this.mapperOutPath.replace(".", File.separator) + File.separator;
				final String outputPathMapper = mapperAbsolutePath + super.getClassName()+"Mapper" + ".java";
				File fileMapper = new File(mapperAbsolutePath);
				if (!fileMapper.exists()) {
					fileMapper.mkdirs();
				}
				
				System.out.println(outputPathMapper);
				FileWriter fwMapper = new FileWriter(outputPathMapper);
				PrintWriter pwMapper = new PrintWriter(fwMapper);
				pwMapper.println(getEntityMapper());
				pwMapper.flush();
				pwMapper.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				pStemt.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		logger.info("end.");
	}

	private String getAbsolutePath() {
		File directory = new File("");
		String path = PropertiesUtil.read("absolutePath", PRO_CONFIG);
		if (path != null && !"".equals(path)) {
			return path;
		}
		return directory.getAbsolutePath();

	}

	
	/**
	 * 功能：获得列的数据类型
	 * 
	 * @param sqlType
	 * @return
	 */
	public String sqlType2JavaType(String sqlType) {
		if (sqlType.equalsIgnoreCase("bit")) {
			return "Boolean";
		} else if (sqlType.equalsIgnoreCase("tinyint")) {
			return "Byte";
		} else if (sqlType.equalsIgnoreCase("smallint")) {
			return "Short";
		} else if (sqlType.equalsIgnoreCase("int")) {
			return "Integer";
		} else if (sqlType.equalsIgnoreCase("bigint")) {
			return "Long";
		} else if (sqlType.equalsIgnoreCase("float")) {
			return "Float";
		} else if (sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("numeric")
				|| sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase("money")
				|| sqlType.equalsIgnoreCase("smallmoney")) {
			return "Double";
		} else if (sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char")
				|| sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar")
				|| sqlType.equalsIgnoreCase("text")) {
			return "String";
		} else if (sqlType.equalsIgnoreCase("datetime") || sqlType.equalsIgnoreCase("timestamp")) {
			return "Date";
		} else if (sqlType.equalsIgnoreCase("image")) {
			return "Blod";
		}else {
		}
		return null;
	}

	public String sqlType2JdbcType(String sqlType) {
		if (sqlType.equalsIgnoreCase("bit")) {
			return "BIT";
		} else if (sqlType.equalsIgnoreCase("tinyint")) {
			return "TINYINT";
		} else if (sqlType.equalsIgnoreCase("smallint")) {
			return "SMALLINT";
		} else if (sqlType.equalsIgnoreCase("int")) {
			return "INTEGER";
		} else if (sqlType.equalsIgnoreCase("bigint")) {
			return sqlType.toUpperCase();
		} else if (sqlType.equalsIgnoreCase("float")) {
			return sqlType.toUpperCase();
		} else if (sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("numeric")
				|| sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase("money")
				|| sqlType.equalsIgnoreCase("smallmoney")) {
			return sqlType.toUpperCase();
		} else if (sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char")
				|| sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar")
				|| sqlType.equalsIgnoreCase("text")) {
			return "VARCHAR";
		} else if (sqlType.equalsIgnoreCase("timestamp")) {
			return "TIMESTAMP";
		} else if (sqlType.equalsIgnoreCase("datetime")) {
			return "TIMESTAMP";
		} else if (sqlType.equalsIgnoreCase("image")) {
			return "IMAGE";
		}
		return null;
	}

}
